﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Hosting;
using CoreClasses;

namespace ProjectCollaborationServerWCF
{
      public class ServiceContract : IServiceContract
    {
        public static string appdata = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "LayoutTool") + "\\";
        public Layout[] GetLayouts()
          {
            
            var list = new List<Layout>();
              foreach (
                  var file in
                      Directory.EnumerateFiles(appdata, "*.layout",
                          SearchOption.AllDirectories))
              {
                  IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                  using (var stream = File.Open(file, FileMode.Open))
                  {
                      var obj = (Layout) formatter.Deserialize(stream);
                      if (obj != null)
                          list.Add(obj);
                      stream.Close();
                  }
              }
              return list.ToArray();

          }

          public Layout GetLayout(string layoutName)
          {
            
            IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
              Layout obj;
              using (var stream = File.Open(appdata + layoutName + ".layout", FileMode.Open))
              {
                  obj = (Layout) formatter.Deserialize(stream);
                  stream.Close();
              }

              return obj;
        }




          public ProjectArea GetProjectArea(string layoutName, string projectArea)
          {

              ProjectArea ret = null;
              foreach (

                  var file in
                      Directory.EnumerateFiles(appdata, "*.area",
                          SearchOption.AllDirectories))
              {
                  IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                  using (var stream = File.Open(file, FileMode.Open))
                  {
                      var obj = (ProjectArea) formatter.Deserialize(stream);
                      if (obj != null && obj.LayoutName == layoutName && obj.ProjectAreaName == projectArea)
                          ret = obj;
                      stream.Close();
                  }
              }
              return ret;
          }

          public void DeleteLayout(string layoutName)
        {


            Directory.CreateDirectory(appdata);

            File.Delete(appdata+ layoutName + ".layout");
            foreach (var file in
                Directory.EnumerateFiles(appdata, "*.area",
                    SearchOption.AllDirectories))
            {
                IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                bool del;
                using (var stream = File.Open(file, FileMode.Open))
                {
                    var obj = (ProjectArea)formatter.Deserialize(stream);
                    del = obj != null && obj.LayoutName == layoutName;
                    stream.Close();
                }
                if(del)
                    File.Delete(file);

            }


        }



        public bool AddLayout(Layout layout)
        {
            try
            {
                
                Directory.CreateDirectory(appdata);
                IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                File.Delete(appdata + layout.LayoutName + ".layout");
                using (Stream stream = new FileStream(appdata + layout.LayoutName + ".layout", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    formatter.Serialize(stream, layout);
                    stream.Close();
                }
                return true;
            }
            catch {  return false;}


        }

        public ProjectArea[] GetProjectAreas(string layoutName)
        {
            var list = new List<ProjectArea>();
            
            foreach (

                var file in
                    Directory.EnumerateFiles(appdata, "*.area",
                        SearchOption.AllDirectories))
            {
                IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                using (var stream = File.Open(file, FileMode.Open))
                {
                    var obj = formatter.Deserialize(stream) ;
                    if (obj != null && (obj as ProjectArea)?.LayoutName == layoutName)
                        list.Add(obj as ProjectArea);
                    stream.Close();
                }
            }
            return list.ToArray();
        }

        public bool AddProjectArea(string layoutName, string projectArea, Rectangle area, byte[] detailedLayout)
        {
            var project = new ProjectArea() {LayoutName = layoutName, ProjectAreaDef = area, ProjectAreaName = projectArea, DetailedLayout = detailedLayout};
            try
            {

                Directory.CreateDirectory(appdata);
                IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                File.Delete(appdata + project.ProjectAreaName + ".area");
                using (Stream stream = new FileStream(appdata + layoutName + project.ProjectAreaName + ".area", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    formatter.Serialize(stream, project);
                    stream.Close();
                }
                return true;
            }
            catch(Exception e)
            {
                return false;
                
            }
        }
        public void DeleteProject(string projectName,string layoutName)
        {


            Directory.CreateDirectory(appdata);

           foreach (var file in
                Directory.EnumerateFiles(appdata, "*.area",
                    SearchOption.AllDirectories))
            {
                IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                bool del;
                using (var stream = File.Open(file, FileMode.Open))
                {
                    var obj = (ProjectArea)formatter.Deserialize(stream);
                    del = obj != null && obj.LayoutName == layoutName && obj.ProjectAreaName == projectName;
                    stream.Close();
                }
                if (del)
                    File.Delete(file);

            }


        }

        public void DeleteGeneralStation(string SyncId)
        {

            Directory.CreateDirectory(appdata);
            File.Delete(appdata + SyncId + ".station");
    
        }



        public bool AddGeneralStation(Station station)
        {
            try
            {

                Directory.CreateDirectory(appdata);
                IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                File.Delete(appdata + station.Name + ".station");
                using (Stream stream = new FileStream(appdata + station.SyncId + ".station", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
                {
                    formatter.Serialize(stream, station);
                    stream.Close();
                }
                return true;
            }
            catch { return false; }
        }

        public Station[] GetGeneralStations()
        {
            var list = new List<Station>();

            foreach (

                var file in
                    Directory.EnumerateFiles(appdata, "*.station",
                        SearchOption.AllDirectories))
            {
                IFormatter formatter = new BinaryFormatter(new SurrogateSelector(), new StreamingContext());
                using (var stream = File.Open(file, FileMode.Open))
                {
                    var obj = formatter.Deserialize(stream);
                    if(obj is Station)
                        list.Add(obj as Station);
                    stream.Close();
                }
            }
            return list.ToArray();
        }

    }
}
